package cn.pzaily.fealetter.job;

import cn.pzaily.fealetter.enumeration.RedisPropertiesKey;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @PackageName: cn.pzaily.fealetter.job
 * @Description:
 * @Author: Pang
 * @Date: 2021-11-24 13:12
 */
@Component
public class ServerRegister implements CommandLineRunner {

    public static String SERVER_ID = null;

    private RedisTemplate redisTemplate;

    public ServerRegister(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void run(String... args) throws Exception {
        // 生成服务ID
        SERVER_ID = UUID.randomUUID().toString().replace("-", "");
        // 注册服务实例
        redisTemplate.opsForHash().put(RedisPropertiesKey.SERVER_ID_HASH, SERVER_ID, System.currentTimeMillis());
    }


    /**
     * 定时服务包括
     * 每三分钟报告一次
     */
    @Scheduled(cron = "1 0/3 * * * ?")
    public void serverReport() {
        redisTemplate.opsForHash().put(RedisPropertiesKey.SERVER_ID_HASH, SERVER_ID, System.currentTimeMillis());
    }

    /**
     * 定时服务检查
     * 每十分钟检查一个服务列表，清空超过五分中没有包括的服务实例
     */
    @Scheduled(cron = "30 0/10 * * * ?")
    public void checkServer() {
        Map serverMap = redisTemplate.opsForHash().entries(RedisPropertiesKey.SERVER_ID_HASH);

        Long startTime = System.currentTimeMillis();
        List removeKeys = new ArrayList<>();

        serverMap.forEach((key, value) -> {
            long time = Long.parseLong(value.toString());
            if (startTime - time > (1000 * 60 * 5)) {
                removeKeys.add(key);
            }
        });

        removeKeys.forEach( key -> {
            redisTemplate.opsForHash().delete(RedisPropertiesKey.SERVER_ID_HASH, key);
        });
    }
}
